//
//  MessageViewController.m
//  UEAssistant
//
//  Created by mac on 2017/3/2.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageTableViewCell.h"
#import "MessageModel.h"
#import "UIView+Badge.h"
@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    NSMutableArray                                                          *_dataSource;
    BOOL                                _isLoadIOver;

}

@property (nonatomic, strong) UITableView                                   *tableView;
@property (nonatomic, strong) UIImageView                                   *view_data_nil;
@property (nonatomic, strong) UILabel                                       *text_data_nil;
@property (nonatomic, assign) NSInteger                                     currentPage;

@end

@implementation MessageViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[MJ_UserMessage sharedInstance] hideBadgeWithMessageButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setData];
}

- (void)setUI{
    
    self.view.backgroundColor = RGB(241, 241, 241, 1);
    self.title = @"消息中心";
    
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:nil] forCellReuseIdentifier:messageTableViewCell];
    self.tableView.rowHeight =  UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 200;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;

}

- (void)setData{
    
    _currentPage = 1;
    _dataSource = [NSMutableArray array];
    [LSProgressHUD showLoadingToView:self.view];
    NSDictionary *dic = @{@"pagesize":@"8",@"pagenum":@"1"};
    NSString *url;
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        url = MessageList_connector_personal;
    }else{
        url = MessageList_connector_enterprise;
    }
    [AvailableNetWorking postWithUrl:url params:dic successHandler:^(id responseObject) {
        
        TGLog(@"message == %@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            
            for (int i = 0; i < ((NSArray *)(responseObject[@"result"])).count; i++) {
                NSDictionary *dic = responseObject[@"result"][i];
                MessageModel *model = [[MessageModel alloc]initWithDictionary:dic];
                [_dataSource addObject:model];
            }
            [LSProgressHUD hiddenLoading:self.view];
            [self.tableView reloadData];
            [self jugeDataIsNil];
        }
        else{
            
            [LSProgressHUD hiddenLoading:self.view];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            [self jugeDataIsNil];
            
        }
    } falureHandler:^(NSError *error) {
        
        [LSProgressHUD hiddenLoading:self.view];
        [self jugeDataIsNil];
        
    }];
    
}

#pragma mark -- <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_dataSource.count > 0) {
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.scrollEnabled = NO;
    }
    return _dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageTableViewCell *cell = [MessageTableViewCell cellWithTableview:tableView];
    cell.model = _dataSource[indexPath.row];
    return cell;
}

- (void)loadNewTopic{
    
    _currentPage = 1;
    _isLoadIOver = NO;
    self.tableView.mj_footer.state = MJRefreshStateIdle;
    NSDictionary *dic = @{@"pagesize":@"8",@"pagenum":@"1"};
    NSString *url;
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        url = MessageList_connector_personal;
    }else{
        url = MessageList_connector_enterprise;
    }
    [AvailableNetWorking postWithUrl:url params:dic successHandler:^(id responseObject) {
        
        TGLog(@"message == %@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            
            TGLog(@"response == %@",responseObject);
            [self.tableView.mj_header endRefreshing];
            [_dataSource removeAllObjects];
            for (int i = 0; i < ((NSArray *)(responseObject[@"result"])).count; i++) {
                NSDictionary *dic = responseObject[@"result"][i];
                MessageModel *model = [[MessageModel alloc]initWithDictionary:dic];
                [_dataSource addObject:model];
            }
            [self.tableView reloadData];
            [self jugeDataIsNil];
        }
        else{
            
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            
            [self jugeDataIsNil];
            
        }
    } falureHandler:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self jugeDataIsNil];
        
    }];
    
}

- (void)loadMoreTopic{
    
    TGLog(@"_currentPage == %ld",(long)_currentPage);
    _currentPage += 1;
    NSString *currentPage = [NSString stringWithFormat:@"%ld",(long)_currentPage];
    NSDictionary *dic = @{@"pagesize":@"8",@"pagenum":currentPage};
    NSString *url;
    if (CurrentUserType == 4 || CurrentUserType == 5) {
        url = MessageList_connector_personal;
    }else{
        url = MessageList_connector_enterprise;
    }
    [AvailableNetWorking postWithUrl:url params:dic successHandler:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            TGLog(@"%@",responseObject);
            if ([responseObject[@"pagecount"] intValue] < (_currentPage - 1)*8) {
                [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"已经加载完全部数据" andTitleColor:[UIColor whiteColor] andCancel:NO];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                _currentPage -= 1;
                _isLoadIOver = YES;
                return;
            }
            else{
                for (int i = 0; i < ((NSArray *)(responseObject[@"result"])).count; i++) {
                    NSDictionary *dic = responseObject[@"result"][i];
                    MessageModel *model = [[MessageModel alloc]initWithDictionary:dic];
                    [_dataSource addObject:model];
                }
                [self.tableView reloadData];
                [self.tableView.mj_footer endRefreshing];
            }
            
        }else{
            _currentPage -= 1;
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            [self.tableView.mj_footer endRefreshing];
        }
    } falureHandler:^(NSError *error) {
        
        [self.tableView.mj_footer endRefreshing];
        
    }];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y + (scrollView.frame.size.height) > scrollView.contentSize.height && !_isLoadIOver) {
        [self.tableView.mj_footer beginRefreshing];
    }
}

#pragma mark -- private
- (void)jugeDataIsNil{
    
    if (_dataSource.count == 0) {
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView addSubview:self.view_data_nil];
        [self.tableView addSubview:self.text_data_nil];
        
    }
    else{
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.view_data_nil removeFromSuperview];
        [self.text_data_nil removeFromSuperview];
        
    }
}


#pragma mark -- getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64) style:UITableViewStylePlain];
        _tableView.backgroundColor = RGB(245, 246, 247, 1);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (UIImageView *)view_data_nil{
    
    if (!_view_data_nil) {
        _view_data_nil = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width/2+50*Radio, Screen_Width/2)];
        _view_data_nil.image = [UIImage imageNamed:@"消息提示"];
        _view_data_nil.center = CGPointMake(self.view.center.x, Screen_Height/3);
    }
    return _view_data_nil;
}

- (UILabel *)text_data_nil{
    
    if (!_text_data_nil) {
        _text_data_nil = [[UILabel alloc]initWithFrame:CGRectMake(0, _view_data_nil.frame.origin.y+_view_data_nil.frame.size.height+20*Radio, Screen_Width, 30)];
        _text_data_nil.backgroundColor = [UIColor clearColor];
        _text_data_nil.text = @"没有消息";
        _text_data_nil.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
        _text_data_nil.textColor = [UIColor grayColor];
        _text_data_nil.textAlignment = NSTextAlignmentCenter;
        
    }
    return _text_data_nil;
}

@end

